如果没有构造函数可用,我如何让我的模板头找到所有myvecs的大小,第一个设置为零,但我不知道如何为myvecB设置大小。 5为myvecC大小设置。 6设置为myvecD大小。
main.cpp
int main()
{
myclass<int> myvecA;
myclass<int> myvecB(10);
myclass<int> myvecC(5,-9);
myclass<string> myvecD(6, "Hi");
cout << "A size: " << myvecA.size() << endl;
cout << "B size: " << myvecB.size() << endl;
cout << "C size: " << myvecC.size() << endl;
cout << "D size: " << myvecD.size() << endl;
system("Pause");
return 0;
}
我的模板类
#include<iostream>
template <class C>
class myclass{
public:
myclass(int x);{
sizearr = x;}
explicit myclass() : sizearr(0) {}
V size();
private:
V sizearr;
};
template <class V>
V myclass<V>::size() {
return sizearr;
}
答案 0 :(得分:1)
您展示的代码充满了错误,无法编译。试试这个:
template <class V>
class myclass {
public:
myclass() : sizearr(0) {}
myclass(int x) : sizearr(x) {}
myclass(int x, const V &v) : sizearr(x) {}
int size();
private:
int sizearr;
};
template <class V>
int myclass<V>::size() {
return sizearr;
}
#include <iostream>
#include <string>
using namespace std;
int main()
{
myclass<int> myvecA;
myclass<int> myvecB(10);
myclass<int> myvecC(5, -9);
myclass<string> myvecD(6, "Hi");
cout << "A size: " << myvecA.size() << endl;
cout << "B size: " << myvecB.size() << endl;
cout << "C size: " << myvecC.size() << endl;
cout << "D size: " << myvecD.size() << endl;
system("Pause");
return 0;
}