为什么一个代码编译了,另一个却失败了
why does one code compiles and the other fails?
此代码符合:
template <class T>
class A {};
void main () {
A<int> a;
vector<A<int>> vec;
vec.push_back(a);
}
但这不是:
void main () {
SharedPointer<int> sp;
vector<SharedPointer<int>> vec;
vec.push_back(sp);
}
我得到这个错误:
错误C2558:类"SharedPointer":没有可用的复制构造函数或复制构造函数被声明为"显式"
SharedPointer标头:(所有方法都在标头中实现)
#include <iostream>
#include "Myexception.h"
using namespace std;
#pragma once
template<class T>
class SharedPointer {
T* ob;
int* refcount;
bool shareable;
int refdown();
int refup();
void markUnshareable();
public:
virtual ~SharedPointer();
SharedPointer():shareable(true);
SharedPointer(T pointee):shareable(true);
SharedPointer(SharedPointer<T>& sp);
SharedPointer operator=(const SharedPointer<T>& sp);
bool operator==(const SharedPointer<T>& sp);
const T& operator[](const int idx) const;
T& operator[](const int idx);
T* operator->() const;
T& operator*() const;
void setOb(T pointee);
const T& getOb() const;
int getRefcount();
bool isShareable();
bool isShared();
};
问题是复制构造函数:
SharedPointer(SharedPointer<T>& sp);
不能仅用于复制const
指针。加上缺失的const
,一切都会好起来:
SharedPointer(const SharedPointer& sp); // <T> is harmless, but unnecessary
(您还必须修复构造函数定义中的语法错误,并且应该将返回类型main
更改为int
。删除using namespace std;
也是一个好主意。)
您的复制构造函数声明了
SharedPointer(SharedPointer<T>& sp);
应该看起来像:
SharedPointer(const SharedPointer<T>& sp);
因此编译器将找到丢失的复制构造函数
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 运行同一解决方案的另一个项目的项目
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- C++从另一个类访问公共静态向量的正确方法是什么
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 使用std::transform将一个范围的元素添加到另一个范围中
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 我可以将一个用clang c++11编译的对象与另一个用c++17编译的对象链接起来吗
- 修改函数中的指针(将另一个指针作为参数传递)
- 为什么我不能将一个对象push_back到属于另一个类的对象向量中?
- C++试图读取一个文件并输出到另一个文本文件
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- xcb_get_image_reply另一个工作区/桌面上的窗口失败
- C++:为什么这个字符串输入失败,而另一个没有
- 类模板中的 typedef 的 SFINAE 失败是指另一个类模板中的 typedef
- C++宏在子类未使用另一个宏时失败
- 为什么当在另一个文件中更改外部常量时,链接器不会失败
- c++从另一个对象赋值失败
- 为什么一个代码编译了,另一个却失败了