小编Mac*_*gma的帖子

指针是否可以指向const空类或非const类?

大概不是.这是我的用例:

我有两个班A和B.

class A
{
    B *b_;
};        

class B
{
public:
    B(): b_string_("") {};

private:    
    std::string b_string_;
};
Run Code Online (Sandbox Code Playgroud)

我希望b_始终指向B对象.我希望b_指向一个"空"B对象而不是nullptr,这样我总是可以以定义的方式取消引用*b_来获得一个空的b _-> b_string.所以我想我会创建一个全局的"null B对象":const B null_b.但我不能(自然地)使用这个A ctor:

A(): b_(&null_b) {};
Run Code Online (Sandbox Code Playgroud)

因为b_不能指向const变量.如果不是"空B对象",则b_需要指向可变B对象.

使全局非const解决问题,但我想保护const,所以我可以保证"null对象"永远不会改变.

FWIW,这涉及一个大型项目,其中b_指向另一个类中B对象的向量.我可以在那个向量中添加一个空的B对象,但这让我觉得很糟糕.

是否有方法或模式来解决我的问题?

c++ pointers

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

如何使用 QLineEdit 使光标从其内容的开头开始?

Windows 7 SP1
MSVS 2010
Qt 4.8.4

这段代码:

#include <QTGui>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QMainWindow*          window = new QMainWindow;
    QLineEdit*         line_edit = new QLineEdit;

    line_edit->setText("ABCDEFG");
    line_edit->setFixedSize(40,20);
    window->setCentralWidget(line_edit);
    window->show();
    return app.exec();
}
Run Code Online (Sandbox Code Playgroud)

显示这个:

在此输入图像描述

请注意,“AB”被截断,并且光标位于行编辑的末尾。

我希望它显示:

在此输入图像描述

这里“FG”被截断,光标位于行编辑的开头。

我尝试设置CursorPosition和cursorBackward但无济于事。如果我通过字体度量的 elidedText 转换文本,它将从头开始显示,并带有尾随“...”。但我不想那样做。

问题:有没有办法让光标在显示 QLineEdit 后从其内容的开头开始?

c++ qt

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

如何在find_if谓词中引用迭代器?

我想确保一个字符串至少有一个alpha.简单:

if ( find_if(field_name.begin(), field_name.end(), isalpha) == field_name.end() )
Run Code Online (Sandbox Code Playgroud)

但我想用一个locale.我知道我可以轻松编写一个单独的函数,但我更喜欢在find_if中使用它.也就是说,

include <locale>

std::locale loc;

if ( find_if(field_name.begin(), field_name.end(), isalpha(*this_iterator,loc) == field_name.end() )
Run Code Online (Sandbox Code Playgroud)

问题:有没有什么可以this_iterator参考当时的迭代器?

c++ iterator

3
推荐指数
2
解决办法
1297
查看次数

为什么Qt在signal/slot中使用无效的类/类型名称引发编译错误?

Windows 7 SP1
MSVS 2010
Qt库4.8.4 for Windows(VS 2010)
Visual Studio加载项1.1.11 for Qt4

起初,我无法弄清楚为什么这个插槽没有触发:

connect (lineEdit, SIGNAL(textChanged(const QString &)),
         this, SLOT(enableFindButton(const Qstring &)));
Run Code Online (Sandbox Code Playgroud)

差异清楚地表明:Qstring应该是QString.

我的问题:为什么要编译?事实上,它将编译为:

connect (lineEdit, SIGNAL(textChanged(const nonsense &)),
         this, SLOT(enableFindButton(const more_nonsense &)));
Run Code Online (Sandbox Code Playgroud)

这是预期的行为吗?为什么这不会引起错误?

qt visual-studio-2010

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

标签 统计

c++ ×3

qt ×2

iterator ×1

pointers ×1

visual-studio-2010 ×1