结构错误与C++

Struct errors with C++?

本文关键字:C++ 错误 结构      更新时间:2023-10-16

所以我正在阅读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;
}
你可以

尝试这样做:-

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

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

test

结构的名称,chris是变量的名称,因此您需要引用chris。您需要单独引用每个字段才能将其打印出来。即:

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

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

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

答案写得很清楚:test.cpp:14:41:错误:在"."令牌之前预期的主要表达式

取代

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

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

那是因为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;

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

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;

你正在打电话给test.chris.

chris 是结构变量的名称。

你想打电话的是chris.name.

test.chris不存在

。 如果要输出整个结构,则需要执行以下操作:

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