小编Gau*_*v K的帖子

理解'try':C++

考虑以下代码:

#include <iostream>
#include <stdexcept>

class E{
    public:
        E(int n):m_n(n)
    {
        if (0>n)
        {
            throw std::logic_error("5");
        }
    }
        ~E(){cout << m_n << "#" <<endl;}
    public :
        int m_n;
};

int main()
{
    try{
        E a(5);
        try{
            E c(7);
            E b(-8);
            E d(9);
        }
        catch(const std::exception &e)
        {
            cout <<2 <<"&&&"<<e.what()<<endl;
            throw e;
        }
    }
    catch(const std::exception &e)
    {
        cout <<3 << "^^^^^ "<<e.what() << endl;
        throw e;
    }
    return 0;
} 
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

7#
2&&&5
5#
3^^^^^ St9exception
std::exception: St9exception
Aborted. …
Run Code Online (Sandbox Code Playgroud)

c++ exception-handling

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

类成员函数的静态互斥锁:C++ 11

参考RAII

我可以使用static mutexcritical section为:

#include <string>
#include <mutex>
#include <iostream>
#include <fstream>
#include <stdexcept>

void write_to_file (const std::string & message) {
    // mutex to protect file access
    static std::mutex mutex;

    // lock mutex before accessing file
    std::lock_guard<std::mutex> lock(mutex);

    // try to open file
    std::ofstream file("example.txt");
    if (!file.is_open())
        throw std::runtime_error("unable to open file");

    // write message to file
    file << message << std::endl;

    // file will be closed 1st when leaving scope (regardless of exception)
    // …
Run Code Online (Sandbox Code Playgroud)

multithreading c++11

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

在c ++中禁用隐式转换

是否可以在C/C++中禁用隐式转换.

假设我想写一个有效函数,只让我输入 integers in range [1,10]

我已经写了:

#include <iostream>


using namespace std;

int main( )
{
    int var=0;
    cout << "Enter a number (Integer between 1 to 10) : ";

    while( (!(cin >> var )) || (var > 10 ) || (var < 1) )
    {
        cout << "U nuts .. It can only be [1,10]\n";
        cin.clear();
        cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        cout << "Enter a number (Integer between 1 to 10) : ";
        }

    cout << "\nYou entered : " << var;

   return …
Run Code Online (Sandbox Code Playgroud)

c++

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

将字符串作为Thread启动例程参数传递:C++

参考http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html#SCHEDULING

我试图在C++中创建两个线程,并尝试将字符串作为参数传递给Thread Start Routine.该Thread Start Routine参数只能(void *)按照定义输入:

int pthread_create(pthread_t * thread, 
                       const pthread_attr_t * attr,
                       void * (*start_routine)(void *), 
                       void *arg);
Run Code Online (Sandbox Code Playgroud)

但我得到以下错误:

$ make
g++ -g -Wall Trial.cpp -o Trial
Trial.cpp: In function `int main()':
Trial.cpp:22: error: cannot convert `message1' from type `std::string' to type `void*'
Trial.cpp:23: error: cannot convert `message2' from type `std::string' to type `void*'
Makefile:2: recipe for target `Trial' failed
make: *** [Trial] Error 1
Run Code Online (Sandbox Code Playgroud)

代码是

#include <iostream>
#include <pthread.h> …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading

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

连接两个字符串:C

考虑下面的代码连接两个char arraysdelimiter:

void addStrings(char* str1,char* str2,char del)
{
//str1=str1+str2
int len1=strlen(str1);
int len2=strlen(str2);
int i=0;
//char* temp=(char*) malloc((len1+1)*sizeof(char));
//strcpy(temp,str1);
str1=(char*) realloc(str1,(len1+len2+1)*sizeof(char));
printf("Here--%d\n",strlen(str1));
*(str1+len1)=del; //adding delimiter
for(i=0;i<=len2;i++)
    *(str1+len1+i+1)=*(str2+i);
printf("Concatenated String: %s\n",str1);
i=0;
    while( *(str1+i) != '\0')
    {
            printf("~~%d:%c\n",i,*(str1+i));
        i++;
    }

}
Run Code Online (Sandbox Code Playgroud)

运行此功能时addStrings("A","test",'@');; 代码崩溃realloc如下gdb output

Breakpoint 3, addStrings (str1=0x40212f <_data_start__+303> "A", str2=0x40212a <_data_start__+298> "test",
    del=64 '@') at string.c:34
34      int len1=strlen(str1);
(gdb) s
35      int len2=strlen(str2);
(gdb) s
36      int i=0;
(gdb) s …
Run Code Online (Sandbox Code Playgroud)

c dynamic-memory-allocation

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

在指定持续时间内运行函数:使用&lt;chrono&gt;的C ++

我需要实现一个函数,该函数应在指定的持续时间内执行指定的任务,并将其作为参数传递给它(std::chrono::milliseconds)

我想出了代码:

void Run(std::chrono::milliseconds ms)
{
    std::chrono::time_point<std::chrono::system_clock> start, end;
    start = std::chrono::system_clock::now();
    std::chrono::duration<double> elapsed_seconds = end - start;
    while (elapsed_seconds <= (ms / 1000))
    {
        std::cout << "Running" << std::endl;
        end = std::chrono::system_clock::now();
        elapsed_seconds = end - start;
    }
}

int main()
{
    {
        std::chrono::milliseconds ms(30000);
        Run(ms);
        system("Pause");
    }
Run Code Online (Sandbox Code Playgroud)

我想将代码打印Running30秒钟,然后退出。但是它没有这样做。我该如何实现这种行为C++ <chrono>

c++ c++11 c++-chrono

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

将图像保存为.jpg文件:Java

我将jFreeChart保存到jpeg文件的方式是:

JFreeChart chart = ChartFactory.createXYLineChart(
"Hysteresis Plot", // chart title
"Pounds(lb)", // domain axis label
"Movement(inch)", // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
); 
Run Code Online (Sandbox Code Playgroud)

然后:

 image=chart.createBufferedImage( 300, 200);
Run Code Online (Sandbox Code Playgroud)

图像显示为: 在此输入图像描述

我的保存功能是:

public static void saveToFile(BufferedImage img)
    throws FileNotFoundException, IOException
    {
        FileOutputStream fos = new FileOutputStream("D:/Sample.jpg");
        JPEGImageEncoder encoder2 =
        JPEGCodec.createJPEGEncoder(fos);
        JPEGEncodeParam param2 =
        encoder2.getDefaultJPEGEncodeParam(img);
        param2.setQuality((float) 200, true);
        encoder2.encode(img,param2);
        fos.close();
    }
Run Code Online (Sandbox Code Playgroud)

我称之为:

try{
            saveToFile(image);
           }catch(Exception e){
           e.printStackTrace();
         }
Run Code Online (Sandbox Code Playgroud)

保存的图像显示为:

在此输入图像描述

任何建议,我错了或如何保存它的方式或可能是我需要保存为.png.任何人都可以让我知道如何保存为.png? …

java

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

为什么选择C++中的dynamic_cast

考虑以下代码:

#include <iostream>

using namespace std;

class Base{
    int i;
    public:
    virtual bool baseTrue() {return true;}
    Base(int i) {this->i=i;}
    int get_i() {return i;}
    };

class Derived : public Base{
    int j;
    public:
    Derived(int i,int j) : Base(i) {this->j=j;}
    int get_j() {return j;}
    };

int main()
{
    Base *bp;
    Derived *pd,DOb(5,10);

    bp = &DOb;

    //We are trying to cast base class pointer to derived class pointer
    cout << bp->get_i() << endl;
    cout << ((Derived *)bp)->get_j() << endl;**//HERE1**

    pd=dynamic_cast<Derived*> (bp); **//HERE2**
    // …
Run Code Online (Sandbox Code Playgroud)

c++

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

通过"指向类成员的指针"访问作为数组的类成员

我写了下面的代码来探索类成员的指针:

#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;

class Sample{
    public:
        int i;
        char name[35];
        char* City;

        Sample(int i,const char* ptr,const char* addr):i(i){
            strncpy(name,ptr,35);
            City= (char*) malloc(strlen(addr)*sizeof(char));
            strcpy(City,addr);
        }
};

int main()
{
    Sample Ob1(1,"Andrew Thomas","Glasgow");
    cout << Ob1.i << " : " << Ob1.name << " lives at : "<< (Ob1.City)<< endl;
    int Sample::*FI=&Sample::i;
    char* Sample::*FCity= &Sample::City;
    char* Sample::*FName=  &Sample::name;

    cout << Ob1.*FI << endl;
    cout << Ob1.*FCity << endl;
    cout << Ob1.*FName << endl;

    return 0; …
Run Code Online (Sandbox Code Playgroud)

c++ pointers class

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

对象的赋值运算符

我编写了一个代码,用于动态分配名称.我知道我应该在这种情况下处理深层复制.我写的是我自己的Copy Constructor,Copy Assignment Operator和析构函数.我应该重新定义任何其他隐式函数,例如移动赋值运算符.我不清楚Move Assignment Operator的概念或任何其他隐式定义的成员函数(除了我已经提到的).任何人都可以为此添加代码dynName code,以显示移动赋值运算符或任何其他隐式成员函数(如果有).

#include <iostream>

using namespace std;

class dynName{
    char* name;
    int size;
    public:

    dynName(char* name="")
    {
        int n=strlen(name)+1;
        this->name= new char[n];
        strncpy(this->name,name,n);
        size=n;
        name[size-1]='\0';//NULL terminated
        cout << "Object created (Constructor) with name : "
        << name << " at address " << &(this->name) << endl;
        }

    dynName(const dynName& Ob)//Copy Constructor
    {
        int n=Ob.size;
        this->name= new char[n];
        strncpy(this->name,Ob.name,n);
        size=n;
        cout << "Object created(Copy constructor) with name : "
        << this->name  << " …
Run Code Online (Sandbox Code Playgroud)

c++ class operator-overloading assignment-operator

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