结构错误与C++
Struct errors with C++?
所以我正在阅读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.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;
既然还没有人提到过,如果你还想用
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;
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'