在c++中传递一个对象作为函数的实参



我有一个简单的程序,它获取两条线(对象)及其系数,如果它们交叉则返回2,如果它们平行则返回1,如果它们是同一条线则返回0。

#include <iostream>
using namespace std;
struct line {
float a;
float b;
} line1, line2;
int lineRelation = (line line1, line line2) {
int answer = 2;
yIntercept1 = line1.b;
yIntercept2 = line2.b;
if (yIntercept1 == yIntercept2 && line1.a == line2.a) {
answer = 0;
} else if (line1.a == line2.a) {
answer = 1;
}
return answer;
};
int main() {

// y = ax + b
line1.a = 4; line1.b = 3;
line2.a = 8; line2.b = 6;
cout<<lineRelation(line1, line2)<<endl;

return 0;
}

然而,当我想编译程序时,我得到以下错误:

g++ /tmp/y3g4MgJxUy.cpp
/tmp/y3g4MgJxUy.cpp:10:26: error: expected primary-expression before 'line1'
10 | int lineRelation = (line line1, line line2) {
|                          ^~~~~
/tmp/y3g4MgJxUy.cpp:10:25: error: expected ')' before 'line1'
10 | int lineRelation = (line line1, line line2) {
|                    ~    ^~~~~~
|                         )
/tmp/y3g4MgJxUy.cpp: In function 'int main()':
/tmp/y3g4MgJxUy.cpp:26:36: error: 'lineRelation' cannot be used as a function
26 |     cout<<lineRelation(line1, line2)<<endl;
|                                    ^

我错在哪里?

你没有正确声明你的函数:

int lineRelation = (line line1, line line2) {

这不是声明函数的正确方式。以main为例。

当我们在这里时,确保通过引用传递对象以提高效率。否则代码将进行不必要的临时拷贝。

更好:

int lineRelation(const line& line1, const line& line2) {
int answer = 2;
yIntercept1 = line1.b;
yIntercept2 = line2.b;
if (yIntercept1 == yIntercept2 && line1.a == line2.a) {
answer = 0;
} else if (line1.a == line2.a) {
answer = 1;
}
return answer;
};

最新更新