我有一个类,其中包含另一个类对象的向量作为成员.在这个类的许多函数中,我必须对向量中的所有对象执行相同的操作:
class Small
{
public:
void foo();
void bar(int x);
// and many more functions
};
class Big
{
public:
void foo()
{
for (size_t i = 0; i < VectorOfSmalls.size(); i++)
VectorOfSmalls[i]->foo();
}
void bar(int x)
{
for (size_t i = 0; i < VectorOfSmalls.size(); i++)
VectorOfSmalls[i]->bar(x);
}
// and many more functions
private:
vector<Small*> VectorOfSmalls;
};
Run Code Online (Sandbox Code Playgroud)
我想简化代码,并找到一种不在每个函数中复制其他向量的方法.
我考虑过创建一个接收函数指针的函数,并在向量的每个成员上调用指向函数.但我不确定在C++中使用函数指针是一个好主意.
我也一直在考虑函子和函数,但它会强迫我为每个函数创建一个类,这听起来像是一种矫枉过正.
另一种可能的解决方案是创建一个接收字符串的函数,并根据字符串调用该命令:
void Big::call_command(const string & command)
{
for (size_t i = 0; i < VectorOfSmalls.size(); i++)
{ …Run Code Online (Sandbox Code Playgroud) /* user-defined exception class derived from a standard class for exceptions*/
class MyProblem : public std::exception {
public:
...
MyProblem(...) { //special constructor
}
virtual const char* what() const throw() {
//what() function
...
}
};
...
void f() {
...
//create an exception object and throw it
throw MyProblem(...);
...
}
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么在()之后有一个"const throw()"?通常,如果有一个throw(),它意味着throw()之前的函数可以抛出异常.但是,为什么抛出这里?
哪一个更好:
public:
const vector<int> & GetPointsVector();
private:
vector<int> PointsVector;
Run Code Online (Sandbox Code Playgroud)
要么:
public:
int GetCurrentPoint();
void MoveToFirstPoint();
void MoveToNextPoint();
bool IsAtLastPoint();
size_t GetNumberOfPoints();
private:
vector<int> PointsVector;
Run Code Online (Sandbox Code Playgroud) 我正在寻找一些STL(但不是boost)容器,在以下操作之后将包含2个元素:"abc"和"xyz":
std::XContainer<string> string_XContainer;
string_XContainer.push_back("abc");
string_XContainer.push_back("abc");
string_XContainer.push_back("xyz");
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我需要它只是为了调用string_XContainer.size()到最后,以获得唯一字符串的总数.所以也许我甚至不需要一个容器,而且有更优雅的方式呢?
void GetarrayElements(int a[]){
int k=0;
while (true){
cout <<"to exit just type a value which is above 100 like ex. 101" << endl;
cout<< "give me the "<< k <<"th element ";
cin >> a[k] >> endl;
if (a[k]<=100 && a[k]>=0){
k+=1;
}
else{
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我试图将一些介于0和100之间的输入值读入数组,我得到了这个错误."不匹配运营商>>".有什么不对?
是否有任何Visual Studio加载项(或windows/unix独立程序)在cpp文件中为头文件中定义的函数(包括类成员函数)创建存根实现?
我正在尝试使用dlopen函数加载动态库.该库包含一个静态对象,它在其构造函数中抛出异常.我在dlopen调用周围有一个"try-catch(...)"块,但它没有捕获异常,我只看到"Abort"打印.
我怎么能抓住这个例外?
std :: vector如何实现对不断变化的元素数量的管理:它是使用realloc()函数还是使用链表?
谢谢.
在Perl中以DDMMYY格式获取文件修改日期的最佳方法是什么?
(最初的问题是"没有DateTime模块怎么做".我删除了这个限制,以使问题更加通用.)
我们为内部客户开发产品.我们没有QA团队,也不使用断言.性能很重要,应用程序大小不重要.
是否有一个配置(而不是分离Debug和Release)是一个好主意,它将具有调试信息(pdbs),并且还将进行性能优化?
这种方法有任何缺点吗?