老实说,我不知道为什么CTable无法转换为CTable?我正在尝试使重载运算符+返回串联的两个表。
错误C2440'正在初始化':无法从'CTable'转换为'CTable'
第二个错误:错误(活动)E0334类“ CTable”没有合适的复制构造函数
#include <iostream>
#include <string>
#include "CTable.h"
int main() {
CTable c_tab_1, c_tab_0;
c_tab_0.vSetValueAt(0, 1);
c_tab_0.vPrint();
c_tab_0.bSetNewSize(4);
c_tab_0.vPrint();
c_tab_1.bSetNewSize(4);
c_tab_0.vSetValueAt(0, 1);
c_tab_0.vSetValueAt(1, 2);
c_tab_0.vSetValueAt(2, 3);
c_tab_0.vSetValueAt(3, 4);
c_tab_0.vPrint();
c_tab_1.vSetValueAt(0, 2);
c_tab_1.vSetValueAt(1, 3);
c_tab_1.vSetValueAt(2, 4);
c_tab_1.vSetValueAt(3, 5);
c_tab_1.vPrint();
c_tab_1.vSetValueAt(2, 123);
c_tab_0.vPrint();
c_tab_1.vPrint();
CTable c_tab_3 = c_tab_0 + c_tab_1; //Error C2440! <-----------------------
c_tab_3.vPrint();
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class CTable {
public:
CTable();
CTable(CTable& pcOther);
CTable* pcClone();
~CTable();
bool bSetNewSize(int iTableLen);
void vSetValueAt(int iOffset, int iNewVal);
void vPrint();
CTable operator+(const CTable& pcNewTable);
private:
string s_name;
int i_size;
int* piTable;
const int SIZE = 10;
const string NAME = "Name";
};
#include <iostream>
#include <string>
#include "CTable.h"
using namespace std;
CTable::CTable() {
s_name = NAME;
cout << "bezp: " << s_name << endl;
piTable = new int[SIZE];
i_size = SIZE;
}
///
CTable::CTable(CTable& pcOther) {
s_name = pcOther.s_name + "_copy";
piTable = new int[pcOther.i_size];
i_size = pcOther.i_size;
for (int i = 0; i < pcOther.i_size; i++) {
piTable[i] = pcOther.piTable[i];
}
cout << "kopiuj: " << s_name << endl;
}
CTable::~CTable() {
delete[] piTable;
cout << "usuwam " << s_name << endl;
}
////
bool CTable::bSetNewSize(int iTableLen) {
if (iTableLen <= 0) {
return false;
}
int* pi_newTable = new int[iTableLen];
memcpy(pi_newTable, piTable, iTableLen);
delete this->piTable;
this->i_size = iTableLen;
this->piTable = pi_newTable;
return true;
}
///
void CTable::vSetValueAt(int iOffset, int iNewVal) {
if (iOffset >= this->i_size) {
return;
}
piTable[iOffset] = iNewVal;
}
void CTable::vPrint() {
for (int i = 0; i < i_size; i++) {
cout << piTable[i] << " ";
}
cout << endl;
}
CTable CTable::operator+(const CTable& pcNewTable) {
CTable result;
int greater_len = i_size < pcNewTable.i_size;
int smaller_len = i_size > pcNewTable.i_size;
int* greater_table = i_size > pcNewTable.i_size ? piTable : pcNewTable.piTable;
int* smaller_table = i_size <= pcNewTable.i_size ? piTable : pcNewTable.piTable;
result.i_size = greater_len;
result.piTable = new int[greater_len];
memcpy(result.piTable, greater_table, greater_len * sizeof(int));
for (int i = 0; i < smaller_len; i++) {
result.piTable[i] += smaller_table[i];
}
return result;
}
我应该纠正什么?
答案 0 :(得分:3)
尝试定义
CTable(const CTable& pcOther)
{
.......
}