2013-02-08 134 views
0
#include <iostream> 
#include <cstring> 
using namespace std; 

struct Student { 
    int no; 
    char grade[14]; 
}; 

void set(struct Student* student); 
void display(struct Student student); 

int main() { 
    struct Student harry = {975, "ABC"}; 

    set(&harry); 
    display(harry); 
} 
void set(struct Student* student){ 
    struct Student jim = {306, "BBB"}; 

    *student = jim; // this works 
    //*student.no = 306; // does not work 
} 
void display(struct Student student){ 

    cout << "Grades for " << student.no; 
    cout << " : " << student.grade << endl; 
} 

我怎樣才能改變結構只是一個成員的指針? * student.no = 306爲什麼不起作用?只是有點困惑。如何更改結構體指針的單個成員的值?

+0

我強烈建議你看看如何用C++改變OOP。 – chris 2013-02-08 21:15:26

回答

3

如果你有一個指向一個結構,你應該使用->訪問它的成員:

student->no = 306; 

這是做(*student).no = 306;語法糖。你的工作原因是因爲operator precedence。如果沒有括號,則.*更高的優先級,你的代碼相當於*(student.no) = 306;

0

operator*具有非常低的優先級,讓你有括號控制評價:

student->no = 306; 

這在我看來是非常容易:

(*student).no = 306; 

雖然它可以隨時爲來完成。

0

您應該使用

student->no = 36 

雖然我們在它,它是不是一個好的做法按值傳遞結構給函數。

// Use typedef it saves you from writing struct everywhere. 
typedef struct { 
    int no; 
// use const char* insted of an array here. 
    const char* grade; 
} Student; 

void set(Student* student); 
void display(Student* student); 

int main() { 
    // Allocate dynmaic. 
    Student *harry = new Student; 
     harry->no = 957; 
     harry->grade = "ABC"; 

    set(harry); 
    display(harry); 
} 
void set(Student *student){ 

    student->no = 306; 
} 
void display(Student *student){ 

    cout << "Grades for " << student->no; 
    cout << " : " << student->grade << endl; 

    delete student; 
}