使用C ++进行结构错误?

时间:2013-09-13 14:55:34

标签: c++ struct

所以我正在阅读C ++入门第6版,并且要使用结构,但是当试图使测试文件运行时,我得到以下错误:

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;
}

8 个答案:

答案 0 :(得分:3)

您可以尝试这样做: -

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

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

答案 1 :(得分:2)

test是结构的名称,chris是变量的名称,因此您需要引用chris。并且您需要单独引用每个字段以将其打印出来。 IE:

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

答案 2 :(得分:1)

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

应为cout << "This is Chris's data:" << chris.name

答案 3 :(得分:1)

答案清楚写明:test.cpp:14:41:错误:在'。'标记之前预期的primary-expression

替换

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

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

答案 4 :(得分:0)

您正在呼叫test.chris

chris是结构变量的名称。

您要致电的是chris.name

答案 5 :(得分:0)

那是因为test.chris不存在。

您希望直接使用chris.namechris.worthchris.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;

答案 6 :(得分:0)

由于还没有人提及它,如果你还想使用

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

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

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;

答案 7 :(得分:-1)

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

std::cout << "This is Chris's Data:  " << chris.name << ", " << chris.age << ", " << chris.worth << std::endl;