小编son*_*yao的帖子

当使用字符串文字初始化时,std :: strings是否以'\ 0'结尾?

我知道字符串对象不是空终止但为什么这应该工作?

std::string S("Hey");
for(int i = 0; S[i] != '\0'; ++i)
   std::cout << S[i];
Run Code Online (Sandbox Code Playgroud)

所以构造函数也复制了null终止符,但是不增加长度?为什么这么麻烦?

c++ string null-terminated subscript-operator

5
推荐指数
2
解决办法
2427
查看次数

在成员函数中返回类对象是什么意思?

我很擅长使用C++进行编程,所以如果这很愚蠢,那就很抱歉.我一直在研究c ++入门书,有些东西我无法理解.以此功能为例:

Sales_data& Sales_data::combine(const Sales_data &rhs)
{
    units_sold += rhs.units_sold;
    revenue += rhs.revenue;
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

我们使用以下方法调用函数:

total.combine(trans);
Run Code Online (Sandbox Code Playgroud)

我得知销售的单位和总对象中的收入将与转换对象中的收入相结合,就像复合赋值运算符(+ =)一样.

我知道这将返回总对象,但我不知道返回总对象意味着什么...

c++ return reference

5
推荐指数
2
解决办法
222
查看次数

如何为类中的模板定义类型别名

例如

struct Option_1
{
    template<class T> using Vector = std::vector<T>;
};
Run Code Online (Sandbox Code Playgroud)

我可以

typename Option_1::Vector<int> v;
Run Code Online (Sandbox Code Playgroud)

但我更喜欢下面的

Vector<Option_1, int> v;
Run Code Online (Sandbox Code Playgroud)

或不带“typename”一词的类似名称。我定义了一个别名

template<class Option, class T> using Vector= typename Option::Vector<T>;
Run Code Online (Sandbox Code Playgroud)

但由于无法识别的模板声明/定义而失败。如何修复它?

c++ templates using c++11 type-alias

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

正确的朋友模板功能的语法

在"C++编程语言"第四版 - 第23.4.7章"朋友"中,我找到了以下示例(我稍微修改了它以仅显示相关部分):

template<typename T>
class Vector {
public:
    friend Vector operator*<>(const Vector& v, int f); 
                           ^^ ~~~~ ?
};

template<typename T>
Vector<T> operator*(const Vector<T>& v, int f) {
    return v;
}
Run Code Online (Sandbox Code Playgroud)

我试图编译它,但我得到以下错误(clang):

main.cpp:8:20: error: friends can only be classes or functions
        friend Vector operator*<>(const Vector& v, int f); 
                      ^
main.cpp:8:29: error: expected ';' at end of declaration list
        friend Vector operator*<>(const Vector& v, int f); 
                               ^
                               ;
2 errors generated.
Run Code Online (Sandbox Code Playgroud)

书解释说:

需要友元函数名称后面的<>来表明朋友是模板函数.如果没有<>,则假定为非模板函数.

这就是全部.

如果没有<>此代码编译,但在使用operator*时(例如Vector<int> v; v*12; …

c++ templates friend

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

带有尾随返回类型的 final、override、const 的语法

我试图覆盖一个 virtual 但也使用关键字override, finaland const,带有尾随返回类型。问题似乎出在派生类上,编译器错误(说我没有指定尾随返回类型)并没有太大帮助。代码在这里:https : //wandbox.org/permlink/zh3hD4Ukgrg6txyE

还贴在下面。我玩过不同的排序,但似乎仍然无法正确。任何帮助将不胜感激,谢谢。

#include<iostream>
using std::cout; using std::endl; using std::ostream;
//////////////////////////////////////////////
//Base stuff
class Base
{
public:
  Base(int i=2):bval(i){}
  virtual ~Base()=default;
  virtual auto debug(ostream& os=cout)const->ostream&;

private:
  int bval=0;
};

auto Base::debug(ostream& os) const->ostream&
{
  os << "bval: " << bval << endl;
  return os;
}

///////////////////////////////////////////////
//Derived stuff
class Derived : public Base
{
public:
  Derived(int i=2,int j=3):Base(i), dval(j){}
  ~Derived()=default;

  auto debug(ostream& os=cout) const override final->ostream&; // error here

private: …
Run Code Online (Sandbox Code Playgroud)

c++ syntax c++11

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

在模板类中编写友元函数声明的正确方法是什么?

我正在尝试编写自己的向量模板类,但是在编写友元函数声明时遇到了一些问题。

一开始我是这样写的:

template <typename T, typename Alloc = std::allocator<T>>
class vector {
public:
    friend bool operator==(const vector<T, Alloc>&, const vector<T, Alloc>&);
};
Run Code Online (Sandbox Code Playgroud)

但是编译器报告了一个警告,我声明了一个非模板函数。所以我把朋友声明改成了这样:

template <typename T, typename Alloc = std::allocator<T>>
class vector {
public:
    template <typename E, typename F>
    friend bool operator==(const vector<E, F>&, const vector<E, F>&);
};
Run Code Online (Sandbox Code Playgroud)

到目前为止一切都很好,但我认为仍然存在问题。如果我这样写,我会创建所有operator==将两个模板参数作为其友元函数的函数。例如,operator==(const vector<int>&, const vector<int>&)andoperator==(const vector<double>&, const vector<double>&)都是vector<int>的友元函数。

在模板类中编写友元函数的正确方法是什么?

c++ templates vector friend

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

C++使用lambda进行隐式构造函数调用,期望函数指针

我试图从lambda函数隐式构造一个对象.对象的构造函数将函数指针作为参数.但是代码[1]不能使用以下消息进行编译:

6 : <source>:6:5: note: candidate constructor not viable: no known conversion from '(lambda at /tmp/compiler-explorer-compiler117117-54-dfxyju.lkw98/example.cpp:22:14)' to 'Bar' (aka 'bool (*)()') for 1st argument
    Foo(Bar b) : m_b{b} {}
Run Code Online (Sandbox Code Playgroud)

但是标准规定lambda函数可以隐式转换为具有相同参数和返回类型的函数指针[2].这应该适用于此,因此我希望构造函数可以调用.

那么代码为什么不编译呢?谢谢你的解释!


[1]代码示例:

using Bar = bool(*)();

class Foo
{
public:
    Foo(Bar b) : m_b{b} {}
private:
    Bar m_b;
};

int main()
{   
    // working
    Foo f1 ( [](){ return true; });
    Foo f2 = Bar( [](){ return true; });

    // working implicit conversion
    bool(*tmp)() = []() { return true; }; …
Run Code Online (Sandbox Code Playgroud)

c++ lambda language-lawyer c++11 c++14

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

将unique_ptr <Object>作为unique_ptr <const Object>返回

我有这样的方法:

std::unique_ptr<const Stats> Table::GetStats() const {
  std::unique_ptr<Stats> result;
  // ...
  // Prepare stats. Under some conditions an exception may be thrown.
  // ...
  return result;
}
Run Code Online (Sandbox Code Playgroud)

问题是它不能编译:

错误:无法将'std :: unique_ptr'左值绑定到'std :: unique_ptr &&'

我可以使用以下旁路进行编译:

return std::unique_ptr<const Stats>(result.release());
Run Code Online (Sandbox Code Playgroud)

但这似乎有点过分.我无法理解,从C++的角度看第一段代码有什么问题?有更优雅的解决方案吗?

c++ const return unique-ptr c++11

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

将成员函数分配给实例成员的属性

我仍然可以在C ++中找到自己的方式,并且遇到了问题。我有一个包含另一个类(不能从其继承)的实例成员的类,其中包括回调。我想将此回调注册到父类,但遇到困难。

经过一番挖掘之后,我了解了方法!=函数,因为一个实例方法隐式地希望它本身有一个实例(我可以描述它的最佳方式!),这std::bind是一个选择,但是当签名为时我无法使它起作用。不<void(void)>

我还阅读了有关实现为接口的方法,类似于委托(我来自Swift背景),这也很有吸引力。

这是我要达到的目标的准系统版本:

class ChildClass
{
public:
    std::function<int(int)> callback;
};

class MainClass
{
public:
    ChildClass childClass;

    MainClass()
    {
        this->childClass.callback = this->square;
    }

private:
    int square(int i)
    {
        return i * i;
    }
};
Run Code Online (Sandbox Code Playgroud)

我知道类型不匹配会导致错误,但是我不知道如何使它们一起玩。

c++ function callback instance c++11

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

std::vector 中 push_back 函数的奇怪语法

我遇到了该push_back函数的以下语法。Vertex只是一个包含三个浮点数 x、y 和 z 的结构。第二行看起来就像会写它。但是第一行对我来说看起来很奇怪。在解释这一点的视频中,据说这是通过成员初始值设定项列表完成的,但它看起来更像是隐式转换。我只是对那里的大括号感到困惑。谁能解释为什么这种语法有效?

std::vector<Vertex> vertices;

vertices.push_back({ 1, 2, 3 });
vertices.push_back(Vertex(1, 2, 3));
Run Code Online (Sandbox Code Playgroud)

c++ initialization stdvector list-initialization

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