0

所以我正在阅读 C++primer 6th edition 并且正在学习结构,但是在尝试运行测试文件时出现以下错误:

xubuntu@xubuntu:~/C/C$ make test
g++     test.cpp   -o test
test.cpp: In function ‘int main()’:
test.cpp:14:41: error: expected primary-expression before ‘.’ token
make: *** [test] Error 1
xubuntu@xubuntu:~/C/C$

编码:

#include <iostream>
#include <stdio.h>

struct test{
        char name[20];
        float age;
        float worth;
};

int main(){
        using namespace std;
        test chris = {"Chris", 22, 22};
        cout << "This is Chris's data:" << test.chris;
        return 0;
}
4

8 回答 8

3

您可以尝试这样做:-

cout << "This is Chris's name:" << chris.name;

test是结构的名称,chris是变量名。

于 2013-09-13T14:59:05.517 回答
2

test是结构chris的名称,是变量的名称,所以你需要引用chris. 您需要单独引用每个字段才能将其打印出来。IE:

cout << "This is Chris's name:" << chris.name;
cout << "This is Chris's age:" << chris.age;
于 2013-09-13T14:58:27.347 回答
1

cout << "This is Chris's data:" << test.chris这是错误的。

它应该是cout << "This is Chris's data:" << chris.name

于 2013-09-13T14:58:30.190 回答
1

答案写得很清楚:test.cpp:14:41: error: expected primary-expression before '.' 令牌

代替

cout << "This is Chris's data:" << test.chris;

    cout << "This is Chris's data:" << chris.name << " " << chris.age;
于 2013-09-13T15:00:17.867 回答
0

你在打电话test.chris

chris是您的结构变量的名称。

您要调用的是chris.name.

于 2013-09-13T14:59:32.540 回答
0

那是因为test.chris不存在。

您想直接使用chris.name, chris.worth, chris.age

如果你想使用类似的东西,std::cout << chris你必须重载<<运算符。例如:

std::ostream& operator<<(std::ostream &stream, const test &theTest) {
     stream << "Name: " << theTest.name << ", Worth: " << theTest.worth << ", Age: " << theTest.age;
     return stream;
}

然后你可以像这样使用它:

    test chris = {"Chris", 22, 22};
    cout << "This is Chris's data:" << chris;
于 2013-09-13T15:28:59.900 回答
0

既然还没有人提到,如果你还想用

cout << "This is Chris's data:" << // TODO

考虑重载输出流运算符“<<”。这将告诉编译器在遇到作为输出流运算符的右操作数的测试对象时要做什么。

struct test{
    char name[20];
    float age;
    float worth;
};

ostream & operator<<(ostream &, const test &);       // prototype

ostream & operator<<(ostream & out, const test & t){ // implementation
    // Format the output however you like
    out << " " << t.name << " " << t.age << " " << t.worth;
    return out;
}

这样这条线现在可以工作了:

cout << "This is Chris's data:" << chris;
于 2013-09-13T15:30:36.403 回答
-1

test.chris不存在。如果要输出整个结构,则需要执行以下操作:

std::cout << "This is Chris's Data:  " << chris.name << ", " << chris.age << ", " << chris.worth << std::endl;
于 2013-09-13T14:59:58.173 回答