小编Dim*_*tic的帖子

在 C++ 中,具有 const 数据成员的类可以没有复制赋值运算符吗?

我正在设计一个类,它应该有一个名为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++ copy-assignment

4
推荐指数
1
解决办法
469
查看次数

C++ 的 auto 关键字是否有助于草率编程,或者是否有原则性的使用?

在 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。我知道这是因为更换autostd::vector<int>::iterator和重新编译产生完全相同的可执行文件。

我发现auto在编译器不同意我认为变量声明应该是什么的情况下很方便,我只是希望它停止抱怨以便我可以继续写作。换句话说,auto当我不太了解我正在编写的代码时,我会使用它,这似乎是一个坏习惯。如果编译器和我在变量的类型上存在分歧,这种分歧可能会渗透并在我的代码中进一步导致更复杂、根深蒂固的错误。这让我想知道auto真正的用途是什么。

auto我上面描述的使用是一种不好的编程习惯,如果是的话,它的一些更原则性的用途是什么?

c++ auto type-deduction

2
推荐指数
1
解决办法
173
查看次数

编译器无法识别模板化类

这是我无法编译的一些代码的精简版本。

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)

c++ templates compiler-errors

1
推荐指数
1
解决办法
53
查看次数

为什么 std::string 似乎做了一些 std::is_convertible 说不可能的事情?

为什么std::to_string允许您将 a 转换doublestd::stringwhen 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)

c++ type-conversion stdstring

-4
推荐指数
1
解决办法
181
查看次数