我正在设计一个类,它应该有一个名为K
. 我也希望这个类有一个复制赋值运算符,但编译器似乎从任何具有 const 数据成员的类中隐式删除了复制赋值运算符。这段代码说明了基本问题:
class A
{
private:
const int K;
public:
A(int k) : K(k) {} // constructor
A() = delete; // delete default constructor, since we have to set K at initialization
A & operator=(A const & in) { K = in.K; } // copy assignment operator that generates the error below
}
Run Code Online (Sandbox Code Playgroud)
这是它生成的错误:
constructor.cpp:13:35: error: cannot assign to non-static data member 'K' with const-
qualified type 'const int'
A & operator=(A const & in) { …
Run Code Online (Sandbox Code Playgroud) 在 C++ 中,auto
关键字强制编译器在编译时推断变量的类型。所以在这个例子中
#include <vector>
int main()
{
std::vector<int> my_vec = {1, 2, 3};
auto my_vec_it = my_vec.begin();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
编译器会推断出my_vec_it
具有 type std::vector<int>::iterator
。我知道这是因为更换auto
用std::vector<int>::iterator
和重新编译产生完全相同的可执行文件。
我发现auto
在编译器不同意我认为变量声明应该是什么的情况下很方便,我只是希望它停止抱怨以便我可以继续写作。换句话说,auto
当我不太了解我正在编写的代码时,我会使用它,这似乎是一个坏习惯。如果编译器和我在变量的类型上存在分歧,这种分歧可能会渗透并在我的代码中进一步导致更复杂、根深蒂固的错误。这让我想知道auto
真正的用途是什么。
auto
我上面描述的使用是一种不好的编程习惯,如果是的话,它的一些更原则性的用途是什么?
这是我无法编译的一些代码的精简版本。
template <typename name_of_type_t> class classA_t
{ /* etc etc etc */ };
template <typename name_of_type_t> class classB_t
{
public:
classA_t<name_of_type_t> && return_new();
};
classA_t<name_of_type_t> && classB_t::return_new() // <-- errors here
{
classA_t<name_of_type_t> * S = new classA_t<name_of_type_t>;
return std::move(*S);
}
int main() { return 0; }
Run Code Online (Sandbox Code Playgroud)
我得到的编译器错误是
template_error.cpp:12:10: error: use of undeclared identifier 'name_of_type_t'
classA_t<name_of_type_t> && classB_t::return_new()
^
template_error.cpp:12:29: error: 'classB_t' is not a class, namespace, or enumeration
classA_t<name_of_type_t> && classB_t::return_new()
^
template_error.cpp:4:42: note: 'classB_t' declared here
template <typename …
Run Code Online (Sandbox Code Playgroud) 为什么std::to_string
允许您将 a 转换double
为std::string
when std::is_convertible_v<double,std::string>
is false
?例如:
#include<iostream>
#include<type_traits>
#include<string>
int main()
{
std::cout << "If double is "
<< (std::is_convertible_v<double,std::string> ? "" : "not ")
<< "convertible to std::string then why is it possible to do this? "
<< std::to_string(3.141592) << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)