[英]Error C2146: syntax error : missing ',' before identifier 'A1'
I am trying to modify the class “cpair” and the function “Add” to be a template class and function. 我试图修改类“cpair”和函数“添加”作为模板类和函数。
#include "stdafx.h"
#include <iostream>
using namespace std;
class cpair
{
public:
cpair(int x=0, int y=0) {A=x; B=y;}
void print()
{cout << A <<" "<<B<<endl;}
int A, B;
};
void Add(cpair A1, cpair A2, cpair &R)
{
R.A= A1.A + A2.A;
R.B= A1.B + A2.B;
}
int _tmain(int argc, _TCHAR* argv[])
{
cpair A1(4,5), A2(1,3), result;
Add(A1, A2, result);
result.print();
return 0;
}
This is my implementation below, but I have an error C2146: syntax error : missing ',' before identifier 'A1'. 这是我在下面的实现,但我有一个错误C2146:语法错误:在标识符'A1'之前缺少','。
#include "stdafx.h"
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class T>
class cpair
{
public:
cpair(T x=0, T y=0) {A=x; B=y;}
void print()
{cout << A <<" "<<B<<endl;}
T A, B;
};
template <class T>
void Add(T cpair A1, T cpair A2, T cpair &R)
{
R.A= A1.A + A2.A;
R.B= A1.B + A2.B;
}
template <class T>
int _tmain(int argc, _TCHAR* argv[])
{
cpair A1(4,5), A2(1,3), result;
Add(A1, A2, result);
result.print();
return 0;
}
How do I convert the class and function to be a template class and function? 如何将类和函数转换为模板类和函数?
Note the correct syntax for using cpair
as class template and defining Add()
as a function template . 请注意使用
cpair
作为类模板并将Add()
定义为函数模板的正确语法。 void Add(T cpair A1, ...
is not a valid syntax, you need to declare Add()
like this: void Add(cpair<T> A1, cpair<T> A2, cpair<T> &R)
. void Add(T cpair A1, ...
不是有效的语法,你需要像这样声明Add()
: void Add(cpair<T> A1, cpair<T> A2, cpair<T> &R)
。
I believe this is a working version of what you wanted: 我相信这是你想要的工作版本:
#include <iostream>
using namespace std;
template <class T>
class cpair
{
public:
cpair(T x = 0, T y = 0) { A = x; B = y; }
void print()
{
cout << A << " " << B << endl;
}
T A, B;
};
template <class T>
void Add(cpair<T> A1, cpair<T> A2, cpair<T> &R)
{
R.A = A1.A + A2.A;
R.B = A1.B + A2.B;
}
int main()
{
cpair<int> A1(4, 5), A2(1, 3), result;
Add(A1, A2, result);
result.print();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.