2013-02-08 62 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; 
} 
相关问题